<template>
	<div class="content-box add-creation">
		<el-steps class="mb24" align-center style="max-width: 80%; margin: auto" :active="step">
			<el-step v-for="(item, index) in steps" :icon="index < step ? 'SuccessFilled' : false" :key="index" :title="item" />
		</el-steps>
		<el-form v-if="step == 0" ref="formRef" :model="form.baseInfo" scroll-to-error :rules="baseInfoRules" label-width="140px">
			<div class="el-form-sub-title">基本信息</div>
			<el-form-item label="活动名称" prop="name">
				<el-input v-model="form.baseInfo.name" placeholder="输入活动名称" />
			</el-form-item>
			<el-form-item label="活动时间" prop="date">
				<el-date-picker v-model="form.baseInfo.date" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" />
			</el-form-item>
			<el-form-item label="背景图片" prop="backgroundImg">
				<uploadImage v-model:file-list="form.baseInfo.backgroundImg" :limit="1" :fileSize="1">
					<template #tip> 建议尺寸:750*1800或等比图片，支持JPG、PNG、JPEG格式</template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="活动规则" prop="rule">
				<el-input type="textarea" rows="3" v-model="form.baseInfo.rule" :maxlength="100" placeholder="输入活动规则" />
			</el-form-item>

			<div class="el-form-sub-title">分享设置</div>
			<el-form-item label="分享好友" prop="enableShare">
				<el-radio-group v-model="form.baseInfo.enableShare" class="good-type">
					<el-radio :value="false"> 关闭</el-radio>
					<el-radio :value="true"> 开启</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="分享图片" prop="shareImg" v-if="form.baseInfo.enableShare">
				<uploadImage v-model:file-list="form.baseInfo.shareImg" :limit="1" :fileSize="1">
					<template #tip> 建议尺寸：600*800或等比图片，支持JPG、PNG、JPEG格式</template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="分享标题" prop="shareTitle" v-if="form.baseInfo.enableShare">
				<el-input v-model="form.baseInfo.shareTitle" placeholder="输入分享标题" />
			</el-form-item>
			<el-form-item label="分享描述" prop="shareDesc" v-if="form.baseInfo.enableShare">
				<el-input v-model="form.baseInfo.shareDesc" placeholder="输入分享描述" />
			</el-form-item>
			<div class="el-form-sub-title">高级设置</div>
			<el-form-item label="参与抽奖限制" prop="limit">
				<el-radio-group v-model="form.baseInfo.limit" class="w-full">
					<el-radio value="ALL"> 所有用户 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="参与条件" prop="condition">
				<el-radio-group v-model="form.baseInfo.condition" class="w-full">
					<el-radio :value="0"> 参与线下活动获取抽奖资格 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="每日次数限制" prop="isEverydayLimit">
				<el-radio-group v-model="form.baseInfo.isEverydayLimit" class="w-full radio-column">
					<el-radio :value="false"> 不限制 </el-radio>
					<el-radio :value="true">
						每人每天可参与
						<el-form-item v-if="form.baseInfo.isEverydayLimit" class="ml10" label="" prop="limitPerDay">
							<el-input-number :controls="false" :precision="0" v-model="form.baseInfo.limitPerDay" />
						</el-form-item>
						<el-form-item v-else class="ml10" label="">
							<el-input-number :controls="false" :precision="0" v-model="form.baseInfo.limitPerDay" />
						</el-form-item>
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="总共次数限制" prop="isTotalLimit">
				<el-radio-group v-model="form.baseInfo.isTotalLimit" class="w-full radio-column">
					<el-radio :value="false"> 不限制 </el-radio>
					<el-radio :value="true">
						每人总共可参与
						<el-form-item v-if="form.baseInfo.isTotalLimit" class="ml10" label="" prop="limitTotal">
							<el-input-number :controls="false" :precision="0" v-model="form.baseInfo.limitTotal" />
						</el-form-item>
						<el-form-item v-else class="ml10" label="">
							<el-input-number :controls="false" :precision="0" v-model="form.baseInfo.limitTotal" />
						</el-form-item>
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" @click="onNext">下一步</el-button>
				</div>
			</el-form-item>
		</el-form>
		<div v-else>
			<div class="mb20">
				<el-tabs class="custom-tabs" v-model="tabCur" type="card" size="small" editable closable @tab-remove="removeTab">
					<template #add-icon>
						<el-button type="primary" class="button-new-tag" link @click="addTag"> + 添加奖品 </el-button>
					</template>
					<el-tab-pane v-for="(item, index) in form.prizeInfos" :key="item.index" :label="`奖品${index + 1}`" :name="index">
						<el-form
							:ref="(el:any) => setformRefs(el, index)"
							:key="item.index"
							:model="form.prizeInfos[index]"
							:rules="prizeInfosRules"
							label-width="140px"
							scroll-to-error
						>
							<el-form-item label="是否兜底奖品" prop="backup">
								<el-radio-group v-model="form.prizeInfos[tabCur].backup" class="w-full">
									<el-radio :value="false"> 否 </el-radio>
									<el-radio :value="true"> 是 </el-radio>
								</el-radio-group>
							</el-form-item>
							<div class="el-form-sub-title">基本信息</div>
							<el-form-item label="奖品名称" prop="name">
								<el-input v-model="form.prizeInfos[tabCur].name" :maxlength="10" placeholder="输入奖品名称(10个字以内)" />
							</el-form-item>
							<el-form-item label="奖品图片" prop="image">
								<uploadImage v-model:file-list="form.prizeInfos[tabCur].image" :limit="1" :fileSize="1">
									<template #tip> 建议尺寸：200*200或等比照片，支持JPG、PNG、JPEG格式</template>
								</uploadImage>
							</el-form-item>
							<el-form-item label="奖品类型" prop="type">
								<el-radio-group v-model="form.prizeInfos[tabCur].type" class="w-full radio-column">
									<!-- <el-radio :value="0">
										积分
										<el-form-item v-if="form.prizeInfos[tabCur].type == 0" class="ml10" label="" prop="prizeBonus">
											<el-input-number :controls="false" v-model="form.prizeInfos[tabCur].prizeBonus" /> </el-form-item
									></el-radio> -->
									<el-radio :value="1"> 实物 </el-radio>
									<el-radio :value="2"> 谢谢惠顾 </el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="奖品排序" prop="sort">
								<el-input-number
									class="num-left"
									:controls="false"
									:precision="0"
									v-model="form.prizeInfos[tabCur].sort"
									placeholder="默认0(越大越靠前)"
								/>
							</el-form-item>
							<el-form-item label="奖品数量" prop="count">
								<el-input-number
									class="num-left"
									:controls="false"
									:precision="0"
									v-model="form.prizeInfos[tabCur].count"
									placeholder="输入奖品数量库存"
								/>
								<span class="ml10">份</span>
							</el-form-item>
							<div class="el-form-sub-title">中奖设置</div>
							<el-form-item label="中奖概率" prop="winRate">
								<el-input-number
									class="num-left"
									:min="0"
									:max="100"
									:precision="2"
									:controls="false"
									v-model="form.prizeInfos[tabCur].winRate"
									placeholder="输入中奖概率"
								/>
								<span class="ml10">%</span>
							</el-form-item>
							<el-form-item label="中奖提示" prop="prompt">
								<el-input v-model="form.prizeInfos[tabCur].prompt" placeholder="输入奖品提示" />
							</el-form-item>
							<!-- <el-form-item label="活动时间" prop="date">
								<el-date-picker v-model="form.prizeInfos[tabCur].date" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" />
							</el-form-item> -->
							<div class="el-form-sub-title">高级设置</div>
							<el-form-item label="每日中奖上限" prop="isLimitPerDay">
								<el-radio-group v-model="form.prizeInfos[tabCur].isLimitPerDay" class="w-full radio-column">
									<el-radio :value="false"> 不限制 </el-radio>
									<el-radio :value="true">
										每日限制
										<el-form-item v-if="form.prizeInfos[tabCur].isLimitPerDay" class="ml10 mr10" label="" prop="limitPerDay">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitPerDay" /> </el-form-item
										><el-form-item v-else class="ml10 mr10" label="">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitPerDay" /> </el-form-item
										>次</el-radio
									>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="每人每日中奖上限" prop="isLimitPerDayOfPerson">
								<el-radio-group v-model="form.prizeInfos[tabCur].isLimitPerDayOfPerson" class="w-full radio-column">
									<el-radio :value="false"> 不限制 </el-radio>
									<el-radio :value="true">
										每日限制
										<el-form-item v-if="form.prizeInfos[tabCur].isLimitPerDayOfPerson" class="ml10 mr10" label="" prop="limitPerDayOfPerson">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitPerDayOfPerson" />
										</el-form-item>
										<el-form-item v-else class="ml10 mr10" label="">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitPerDayOfPerson" /> </el-form-item
										>次</el-radio
									>
								</el-radio-group> </el-form-item
							><el-form-item label="每人累计中奖上限" prop="isLimitTotalOfPerson">
								<el-radio-group v-model="form.prizeInfos[tabCur].isLimitTotalOfPerson" class="w-full radio-column">
									<el-radio :value="false"> 不限制 </el-radio>
									<el-radio :value="true">
										每人限制
										<el-form-item v-if="form.prizeInfos[tabCur].isLimitTotalOfPerson" class="ml10 mr10" label="" prop="limitTotalOfPerson">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitTotalOfPerson" /> </el-form-item
										><el-form-item v-else class="ml10 mr10" label="">
											<el-input-number :controls="false" :precision="0" v-model="form.prizeInfos[tabCur].limitTotalOfPerson" /> </el-form-item
										>次</el-radio
									>
								</el-radio-group>
							</el-form-item>
							<el-form-item label-width="0">
								<div class="flex-start w-full">
									<el-button @click="onPre">上一步</el-button>
									<el-button type="primary" v-debounce="onSubmit">保存</el-button>
								</div>
							</el-form-item>
						</el-form>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
	</div>
</template>

<script setup lang="tsx" name="addLottery">
import { ref, reactive, onBeforeMount, onMounted } from 'vue';
import { ElMessage, type FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import dayjs from 'dayjs';
import uploadImage from '/@/components/upload/image.vue';
// import RefreshSelect from '/@/components/refreshSelect/index.vue';
import { fetchCreateLottery, fetchUpdateLottery, fetchLotteryDetail } from '/@/api/lottery';

const route = useRoute();
const router = useRouter();

const step = ref(0);

const tabCur = ref(0);

const steps = ['基础设置', '奖品设置'];

const formRef = ref();
const formRefMap = ref<any[]>([]);
const form = reactive<any>({
	baseInfo: {
		limit: 'ALL',
		enableShare: true,
		condition: 0,
		isEverydayLimit: false,
		isTotalLimit: false,
	},
	prizeInfos: [
		{ index: dayjs().format('x'), backup: false, type: 0, isLimitPerDay: false, isLimitPerDayOfPerson: false, isLimitTotalOfPerson: false },
	],
});

const setformRefs = (ref: any, index: number) => {
	formRefMap.value[index] = ref;
};

const removeTab = (targetName: any) => {
	const tabs = form.prizeInfos;
	let activeName = tabCur.value;
	if (targetName <= activeName && targetName !== 0) {
		activeName--;
	}
	tabCur.value = activeName;
	tabs.splice(targetName, 1);
};

//校验规则
const baseInfoRules = reactive<FormRules<any>>({
	name: [{ required: true, message: '活动名称不能为空', trigger: ['change', 'blur'] }],
	date: [{ required: true, message: '活动时间不能为空', trigger: ['change', 'blur'] }],
	backgroundImg: [{ required: true, message: '背景图片不能为空', trigger: ['change', 'blur'] }],
	rule: [{ required: true, message: '活动规则不能为空', trigger: ['change', 'blur'] }],
	limit: [{ required: true, trigger: 'blur', message: '参与抽奖限制不能为空' }],
	enableShare: [{ required: true, trigger: 'blur', message: '分享好友不能为空' }],
	shareImg: [{ required: true, trigger: 'blur', message: '分享图片不能为空' }],
	shareTitle: [{ required: true, trigger: 'blur', message: '分享标题不能为空' }],
	condition: [{ required: true, message: '参与条件不能为空', trigger: ['change', 'blur'] }],
	isEverydayLimit: [{ required: true, message: '每日次数限制不能为空', trigger: ['change', 'blur'] }],
	limitPerDay: [{ required: true, message: '每人每天可参与数不能为空', trigger: ['change', 'blur'] }],
	isTotalLimit: [{ required: true, message: '总共次数限制不能为空', trigger: ['change', 'blur'] }],
	limitTotal: [{ required: true, message: '每人总共可参与数不能为空', trigger: ['change', 'blur'] }],
});

const prizeInfosRules = reactive<FormRules<any>>({
	backup: [{ required: true, message: '是否兜底奖品不能为空', trigger: ['change', 'blur'] }],
	name: [{ required: true, message: '奖品名称不能为空', trigger: ['change', 'blur'] }],
	image: [{ required: true, message: '奖品图片不能为空', trigger: ['change', 'blur'] }],
	type: [{ required: true, message: '奖品类型不能为空', trigger: ['change', 'blur'] }],
	prizeBonus: [{ required: true, message: '奖品积分不能为空', trigger: ['change', 'blur'] }],
	count: [{ required: true, message: '奖品不能为空', trigger: ['change', 'blur'] }],
	winRate: [{ required: true, message: '中奖概率不能为空', trigger: ['change', 'blur'] }],
	prompt: [{ required: true, message: '中奖提示不能为空', trigger: ['change', 'blur'] }],
	isLimitPerDay: [{ required: true, message: '每日中奖上限不能为空', trigger: ['change', 'blur'] }],
	limitPerDay: [{ required: true, message: '每日限制数不能为空', trigger: ['change', 'blur'] }],
	isLimitPerDayOfPerson: [{ required: true, message: '每人每日中奖上限不能为空', trigger: ['change', 'blur'] }],
	limitPerDayOfPerson: [{ required: true, message: '每人限制数不能为空', trigger: ['change', 'blur'] }],
	isLimitTotalOfPerson: [{ required: true, message: '每人累计中奖上限不能为空', trigger: ['change', 'blur'] }],
	limitTotalOfPerson: [{ required: true, message: '每人累计限制数不能为空', trigger: ['change', 'blur'] }],
});

const editId = ref();

const formatParams = (data: any) => {
	const { baseInfo, prizeInfos } = JSON.parse(JSON.stringify(data));
	return {
		baseInfo: {
			id: editId.value || '',
			...baseInfo,
			backgroundImg: baseInfo.backgroundImg.map((item: any) => item.url).join(),
			shareImg: baseInfo.shareImg ? baseInfo.shareImg.map((item: any) => item.url).join() : '',
			startTime: dayjs(baseInfo.date[0]).format('YYYY-MM-DD HH:mm:ss'),
			endTime: dayjs(baseInfo.date[1]).format('YYYY-MM-DD HH:mm:ss'),
		},
		prizeInfos: prizeInfos.map((item: any) => {
			return {
				...item,
				image: item.image.map((item: any) => item.url).join(),
			};
		}),
	};
};

const addTag = (data: any) => {
	form.prizeInfos.push({
		index: dayjs().format('x'),
		backup: false,
		type: 0,
		isLimitPerDay: false,
		isLimitPerDayOfPerson: false,
		isLimitTotalOfPerson: false,
	});
	tabCur.value = form.prizeInfos.length - 1;
};

const onPre = () => {
	step.value--;
};

const onNext = () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			step.value++;
		}
	});
};

const onSubmit = async () => {
	const promisArr: any = formRefMap.value.map((formRef: any, index: any) => {
		return formRef.validate(async (valid: boolean) => {});
	});
	const res = await Promise.all(promisArr);

	const valid = res.every((item) => item);
	if (valid) {
		const params = formatParams(form);
		const sum = params.prizeInfos.reduce(function (acc: number, obj: any) {
			return acc + Number(obj.winRate);
		}, 0);
		if (sum > 100) {
			ElMessage.error('中奖概率总计不能大于100%');
			return;
		}
		const res = await (editId.value
			? fetchUpdateLottery({ ...params, id: params.baseInfo.id, name: params.baseInfo.name })
			: fetchCreateLottery({ ...params, id: params.baseInfo.id, name: params.baseInfo.name }));
		if (res.code == 200) {
			ElMessage.success(editId.value ? '编辑成功' : '新增成功');
			back();
		} else {
			ElMessage.error(res.msg);
		}
	} else {
		if (res[tabCur.value]) {
			const index = res.findIndex((item) => !item);
			if (index != -1) {
				tabCur.value = index;
				formRefMap.value[index].validate();
			}
		}
	}
};

const back = () => {
	router.push('/lottery/list');
};

onMounted(async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const res = await fetchLotteryDetail({ id: editId.value });
		if (res.code === 200) {
			const { baseInfo, prizeInfos } = res.data;
			baseInfo.backgroundImg = baseInfo.backgroundImg.split(',').map((item: any) => {
				return {
					url: item,
				};
			});
			baseInfo.shareImg = baseInfo.shareImg
				? baseInfo.shareImg.split(',').map((item: any) => {
						return {
							url: item,
						};
				  })
				: '';
			baseInfo.date = [baseInfo.startTime, baseInfo.endTime];
			baseInfo.limit = 'ALL';
			baseInfo.condition = 0;
			form.baseInfo = baseInfo;
			form.prizeInfos = prizeInfos.map((item: any) => {
				return {
					...item,
					image: item.image.split(',').map((item: any) => {
						return {
							url: item,
						};
					}),
					// date: [item.startTime, item.endTime],
				};
			});
		}
	}
});
</script>

<style scoped lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number {
			max-width: 450px;
		}
	}
}
</style>
<style lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-input-number,
		.el-select,
		.el-date-editor,
		.el-cascader,
		.el-textarea,
		.refresh-select-wrapper {
			width: 100%;
			max-width: 450px;
		}
	}
}
.custom-tabs {
	.el-tabs__header,
	.el-tabs__item {
		height: 40px;
	}

	.el-tabs__new-tab {
		min-width: max-content;
		border: 0;
		margin-top: 10px;
	}
}
</style>
